package com.itheima.security;

import com.itheima.health.pojo.Permission;
import com.itheima.health.service.UserService;
import com.itheima.health.vo.RoleVO;
import com.itheima.health.vo.UserVO;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class HealthUserDetilServiceImpl implements UserDetailsService {

    @Reference
    private UserService userService;

    //根据用户账号名查询用户的角色关键字以及权限关键字,封装到UserDetails中,后期既可以使用角色关键字,也可以使用权限关键字
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    //涉及的表有:t_user,t_user_role,t_role,t_role_permission,t_premission
        //1.根据用户名称查询用户表,得到用户的ID
        //2.根据用户的ID,通过中间表,可以查询得到用户的角色
        //3.根据用户的角色ID,通过中间表可以查询得到用户的权限
        UserVO userVO = userService.findUserDetailsByUsername(username);
        if (userVO == null) {
            return null;
        }

        //创建一个集合封装所有权限
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<GrantedAuthority>();
        //获取用户的所有角色
        List<RoleVO> roles = userVO.getRoles();
        //遍历用户的所有角色,获取每个角色的权限
        for (RoleVO role : roles) {
            //放入角色关键字
            grantedAuthorityList.add(new SimpleGrantedAuthority(role.getKeyword()));
            //放入权限关键字
            List<Permission> permissionSet = role.getPermissionList();
            for (Permission permission : permissionSet) {
                grantedAuthorityList.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        return new User(username, userVO.getPassword(), grantedAuthorityList);
    }
}
